<template>
  <div class="app-container">
    <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="4" :lg="4" :xl="4"> 
          <div class="head-container">
                <el-input
                  v-model="filterText"
                  placeholder="输入部门名称搜索"
                  size="small"
                  prefix-icon="el-icon-search"
                  class="filter-item"
                  style="margin-bottom: 20px"
                />
                <el-tree :data="deptData" :props="deptTreeProps" 
                :expand-on-click-node="false"
                :default-expand-all="true"
                @node-click="handleNodeClick"
                ></el-tree>

          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="20" :lg="20" :xl="20"> 
          <div class="filter-container">
               <el-input
                  v-model="keyword"
                  clearable
                  placeholder="请输入用户名"
                  size="small"
                  prefix-icon="el-icon-search"
                  class="filter-item"
                  style=" width: 200px;"
                />
                <el-button class="filter-item" type="primary" icon="el-icon-search" size="mini" @click="handleSearch">查找
                </el-button>
                <el-button class="filter-item" type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">添加
                </el-button>
          </div>
          <el-table  v-loading="loading" :data="tableData" style="width: 100%" size="mini">
              <el-table-column label="序号" width="60" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>

               <el-table-column label="用户名" width="80" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>

          <el-table-column label="手机号" width="100" align="center" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.phone }}</span>
            </template>
          </el-table-column>

          <el-table-column label="邮箱" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>

          <el-table-column label="部门 / 岗位" width="130" align="center">
            <template slot-scope="scope">
              <div>{{ scope.row.deptName }} / {{ scope.row.jobName }}</div>
            </template>
          </el-table-column>

          <el-table-column label="拥有角色" width="200" align="center">
            <template slot-scope="scope">
              <el-tag v-for="item in scope.row.roleList" :key="item.roleId" type="success" style="margin-right: 5px;">
                {{ item.roleName }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="70" align="center">
            <template slot-scope="scope">
              <div v-for="item in dicts" :key="item.id">
                <el-tag v-if="'user_status_'+scope.row.status.toString() === item.value" :type="scope.row.status ? '' : 'info'">
                  {{item.label }}
                </el-tag>
              </div>
            </template>

          </el-table-column>

          <el-table-column label="操作" fixed="right" min-width="120" align="center">
            <template slot-scope="scope">
              <el-button @click="handRest(scope.row)" type="warning" size="small">重置密码</el-button>
              <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)" >编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete"  @click="handleDelete(scope.row)" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="block">
          <el-pagination
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, prev, pager, next,sizes, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="!dataForm.id ? '新增用户' : '修改用户'" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            <el-form :model="dataForm" :rules="rules" label-width="80px" size="small"  style="text-align:left;"> 
                <el-form-item label="用户名"  prop="username">
                  <el-input v-model="dataForm.username" auto-complete="off" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="邮箱"  prop="email" >
                  <el-input v-model="dataForm.email" auto-complete="off" placeholder="请输入邮箱" />
                </el-form-item>

                <el-form-item label="手机"  prop="phone" >
                  <el-input v-model="dataForm.phone" auto-complete="off" placeholder="请输入手机" />
                </el-form-item>
                

                <el-form-item label="部门"   >
                  <popup-tree-input
                    :data="deptData"
                    :props="deptTreeProps"
                    :prop="dataForm.deptName"
                    :node-key="''+dataForm.deptId"
                    :current-change-handle="deptTreeCurrentChangeHandle"
                  />
                </el-form-item>

                <el-form-item label="岗位" >
                  <el-select v-model="dataForm.jobId" placeholder="请先选择部门" style="width: 100%">
                    <el-option
                      v-for="(item,index) in jobs"
                      :key="''+ index"
                      :label="item.jobName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="角色" prop="userRoles"  >
                  <el-select v-model="dataForm.roleList" multiple placeholder="请选择" style="width: 100%;">
                    <el-option
                      v-for="item in roles"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status"  >
                  <el-switch
                    v-model="dataForm.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="正常"
                    active-value="1"
                    inactive-text="锁定"
                    inactive-value="2"
                  />
                </el-form-item>
             </el-form>
             <div slot="footer"  class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
             </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import { getUserList,addUser,editUser,deleteUser,restPass } from '@/api/user'
  import { getRoleList } from '@/api/roles'
  import { getJobListByDeptId } from '@/api/job'
  import { getDept } from '@/api/dept'
  import initDict from '@/mixins/initDict'
  import PopupTreeInput from '@/components/PopupTreeInput'

  export default {
     //注册组件
     components: {
       PopupTreeInput
     },
     mixins: [initDict],
     data() {
        // 验证手机号是否合法
        const checkTel = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入手机号码'))
          } else if (!this.checkMobile(value)) {
            callback(new Error('手机号码不合法'))
          } else {
            callback()
          }
        }
        return {
          deptData: [],
          deptTreeProps: {
            label: 'name',
            children: 'children'
          },
          //搜索数据
          filterText:'',
          //加载图表
          loading: false,
          //用户列表
          tableData:[],
          roles: [], // 角色列表
          //岗位
          jobs:[],
          currentPage: 1,
          pageSize: 10,
          total: 0, // 总数量
          deptId: 0,
          keyword: '',
          //弹框显示的标题
          dialogFormVisible: false, // 控制弹出框
          //表单标签
          formLabelWidth: '120px',
          dataForm: {
            id:0,
            username: '',
            avatar: '',
            deptId: 0,
            deptName: '',
            jobId: null,
            email: 'qq1328312923@163.com',
            phone: '15728046328',
            status: '' + 1,
            roleList: []
          },
          rules: {
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { pattern: /^[a-zA-Z0-9_]{4,8}$/, message: '以字母开头，长度在4-8之间， 只能包含字符、数字和下划线' }],
            phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkTel, trigger: 'change' }],
            email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '输入邮箱不合法'
            }]
          },

        }
        
     },
     created() {
        this.getDeptTree()
        this.adminList()
        this.getUserRoles()
        // 加载数据字典
        this.getDict('user_status')
     },
     methods: {
        //表单重置
        resetDataForm: function() {
          this.dataForm = {
            username: '',
            avatar: '',
            deptId: 1,
            deptName: '',
            jobId: null,
            email: 'qq1328312923@163.com',
            phone: '15728046328',
            status: '' + 1,
            roleList: []
          }
        },
        // 加载用户角色信息
        getUserRoles: function() {
          const params = new URLSearchParams()
          params.append('roleName', '')
          getRoleList(params).then((res) => {
            this.roles = res.data.data
          })
        },
        // 加载部门列表
        getDeptTree: function() {
          getDept().then((res) => {
            this.deptData = res.data.data
          })
        },
         // 加载用户列表
        adminList: function() {
          this.loading = true
          const params = new URLSearchParams()
          params.append('page', this.currentPage)
          params.append('pageSize', this.pageSize)
          params.append('deptId', this.deptId)
          params.append('username', this.keyword)
          getUserList(params).then(response => {
            this.loading = false
            this.tableData = response.data.data.records
            this.total = response.data.data.total
          })
        },
        //部门树点击事件
        handleNodeClick:function(data){
          this.deptId = data.id === 0 ? 0 : data.id
          this.adminList()
        },
        //处理搜索
        handleSearch:function(){
          this.adminList()
        },
        //处理添加
        handleAdd:function(){
          this.resetDataForm();
          //显示dialog
          this.dialogFormVisible = true
        },
         // 编辑
        handleEdit: function(row) {
          this.dialogFormVisible = true
          this.dataForm = Object.assign({}, row)
          this.dataForm.status = row.status+'';
          this.getJobs(row.deptId)
          // 设置选择的角色列表
          const userRoles = []
          for (let i = 0, len = row.roleList.length; i < len; i++) {
            userRoles.push(row.roleList[i].id)
          }
          this.dataForm.roleList = userRoles
        },
        // 部门菜单树选中
        deptTreeCurrentChangeHandle(data) {
          this.dataForm.deptId = data.id
          this.dataForm.deptName = data.name
          this.getJobs(data.id)
        },
        // 加载岗位列表
        getJobs(id) {
          getJobListByDeptId(id).then(res => {
            this.jobs = res.data.data
          })
        },
        //提交修改
        submitForm: function() {
          const userRoles = []
          for (let i = 0, len = this.dataForm.roleList.length; i < len; i++) {
            userRoles.push(this.dataForm.roleList[i])
          }
          this.dataForm.roleList = userRoles
          if(this.dataForm.id){
            // 编辑用户
            editUser(this.dataForm).then(response => {
                if (response.data.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  })
                  this.dialogFormVisible = false
                  this.adminList()
                } else {
                  this.$message({
                    type: 'error',
                    message: response.data.msg
                  })
                }
            })
          }else{
            // 添加用户
            addUser(this.dataForm).then(response => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.dialogFormVisible = false
                this.adminList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg
                })
              }
            })
          }
        },
         // 删除用户
        handleDelete: function(row) {
          const that = this
          this.$confirm('此操作将该管理员删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              deleteUser(row.id).then(response => {
                if (response.data.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  })
                  that.adminList()
                } else {
                  this.$message({
                    type: 'error',
                    message: response.data.msg
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        },
        // 密码重置 
        handRest: function(row) {
          const that = this
          this.$confirm('此操作将会将该用户密码重置, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              restPass(row.id).then(response => {
                if (response.data.code === 200) {
                  that.$message({
                    type: 'success',
                    message: '重置密码成功'
                  })
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.msg
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '重置密码取消'
              })
            })
        },
        // 换页
        handleCurrentChange: function(val) {
          this.currentPage = val
          this.adminList()
        },
        // 换页数
        handleSizeChange(val) {
          this.pageSize = val
          this.adminList()
        }
     }
  }
</script>